/* eslint-disable no-useless-escape */
import {
    resetpwd,
    sendCaptcha,
    sendCaptchaEmail,
} from '@/servers/api/userController';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import {
    LoginForm,
    ProFormCaptcha,
    ProFormInstance,
    ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, getLocale, useIntl } from '@umijs/max';
import { message, theme } from 'antd';
import { Dispatch, SetStateAction, useRef, useState } from 'react';
const Logo = require('@/assets/logo.png');
const regE =
    /(?=^.{3,256}$)^([\w\-]+([\.][\w\-]+)*)@[a-zA-Z0-9][a-zA-Z0-9\-]*[\.][A-Za-z]{2,6}$/;
type IProps = {
    setnowPage: Dispatch<SetStateAction<string>>;
};
const Forget: React.FC<IProps> = (props) => {
    const formRef = useRef<ProFormInstance>();
    const [lang, setlang] = useState(getLocale());
    const { token } = theme.useToken();
    const intl = useIntl();
    const onFinish = async (values: any) => {
        let parmas = {
            ...values,
            type: lang === 'zh-CN' ? 'mobile' : 'email',
            newpassword: values.password_repeat,
        };
        delete parmas.password_repeat;
        delete parmas.password;
        resetpwd(parmas)
            .then((res) => {
                message.success(intl.formatMessage({ id: '注册成功' }));
                props.setnowPage('');
            })
            .catch((err) => {
                console.log(err);
                message.error(err.msg);
            });
    };
    const toForget = () => {
        props?.setnowPage('');
    };
    async function getCode() {
        if (lang === 'zh-CN') {
            const mobile = formRef?.current?.getFieldValue('mobile');
            if (!mobile) {
                message.error(intl.formatMessage({ id: '请输入手机号' }));
                throw new Error('获取验证码错误');
            }
            const reg = /^[0-9]{11}$/;
            if (!reg.test(mobile)) {
                message.error(intl.formatMessage({ id: '手机号格式错误' }));
                throw new Error('获取验证码错误');
            }
            await sendCaptcha({
                mobile: mobile,
                event: 'resetpwd',
            });
        } else {
            const email = formRef?.current?.getFieldValue('email');
            if (!email) {
                message.error(intl.formatMessage({ id: '请输入邮箱' }));
                throw new Error('请输入邮箱');
            }
            if (!regE.test(email)) {
                message.error(intl.formatMessage({ id: '邮箱格式错误' }));
                throw new Error('邮箱格式错误');
            }
            await sendCaptchaEmail({
                email: email,
                event: 'resetpwd',
            });
        }
    }
    return (
        <LoginForm
            formRef={formRef}
            onFinish={onFinish}
            logo={Logo}
            title="GLUZ"
            contentStyle={{
                background: '#fff',
                padding: '20px',
                borderRadius: '10px',
                width: '400px',
            }}
            containerStyle={{
                backdropFilter: 'blur(4px)',
                backgroundImage:
                    'url(https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp)',
                backgroundSize: 'cover',
            }}
            subTitle={intl.formatMessage({ id: '忘记密码' })}
            submitter={{
                searchConfig: {
                    submitText: intl.formatMessage({ id: '提交' }),
                },
            }}
        >
            {lang === 'zh-CN' && (
                <ProFormText
                    name="mobile"
                    fieldProps={{
                        size: 'large',
                        prefix: (
                            <UserOutlined
                                style={{
                                    color: token.colorText,
                                }}
                                className={'prefixIcon'}
                            />
                        ),
                    }}
                    placeholder={intl.formatMessage({
                        id: '请输入手机号',
                    })}
                    rules={[
                        {
                            required: true,
                            message: intl.formatMessage({
                                id: '请输入手机号',
                            }),
                        },
                        {
                            pattern: /^[0-9]{11}$/,
                            message: intl.formatMessage({
                                id: '手机号格式错误',
                            }),
                        },
                    ]}
                />
            )}
            {lang === 'ru-RU' && (
                <ProFormText
                    name="email"
                    fieldProps={{
                        size: 'large',
                        prefix: (
                            <UserOutlined
                                style={{
                                    color: token.colorText,
                                }}
                                className={'prefixIcon'}
                            />
                        ),
                    }}
                    placeholder={intl.formatMessage({
                        id: '请输入邮箱',
                    })}
                    rules={[
                        {
                            required: true,
                            message: intl.formatMessage({
                                id: '请输入邮箱',
                            }),
                        },
                        {
                            pattern: regE,
                            message: intl.formatMessage({
                                id: '邮箱格式错误',
                            }),
                        },
                    ]}
                />
            )}
            <ProFormText.Password
                name="password"
                fieldProps={{
                    size: 'large',
                    prefix: (
                        <LockOutlined
                            style={{
                                color: token.colorText,
                            }}
                            className={'prefixIcon'}
                        />
                    ),
                }}
                placeholder={intl.formatMessage({
                    id: '请输入密码',
                })}
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: '请输入密码',
                        }),
                    },
                    {
                        pattern: /^.{7,15}$/,
                        message: intl.formatMessage({
                            id: '请设置6-15位密码',
                        }),
                    },
                ]}
            />
            <ProFormText.Password
                name="password_repeat"
                fieldProps={{
                    size: 'large',
                    prefix: (
                        <LockOutlined
                            style={{
                                color: token.colorText,
                            }}
                            className={'prefixIcon'}
                        />
                    ),
                }}
                placeholder={intl.formatMessage({
                    id: '再次确认密码',
                })}
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: '再次确认密码',
                        }),
                    },
                    ({ getFieldValue }) => ({
                        validator(_, value) {
                            if (!value || getFieldValue('password') === value) {
                                return Promise.resolve();
                            }
                            return Promise.reject(
                                new Error(
                                    intl.formatMessage({
                                        id: '两次密码不一致',
                                    }),
                                ),
                            );
                        },
                    }),
                ]}
            />
            <ProFormCaptcha
                fieldProps={{
                    size: 'large',
                    prefix: (
                        <LockOutlined
                            style={{
                                color: token.colorText,
                            }}
                            className={'prefixIcon'}
                        />
                    ),
                }}
                captchaProps={{
                    size: 'large',
                }}
                placeholder={intl.formatMessage({
                    id: '请输入验证码',
                })}
                captchaTextRender={(timing, count) => {
                    if (timing) {
                        return `${count} ${intl.formatMessage({
                            id: '获取验证码',
                        })}`;
                    }
                    return intl.formatMessage({
                        id: '获取验证码',
                    });
                }}
                name="captcha"
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: '请输入验证码',
                        }),
                    },
                ]}
                onGetCaptcha={async () => {
                    await getCode();
                }}
            />
            <div style={{ marginBlockEnd: 24 }}>
                <a>&nbsp;</a>
                <a style={{ float: 'right' }} onClick={toForget}>
                    <FormattedMessage id="登录"></FormattedMessage>
                </a>
            </div>
        </LoginForm>
    );
};
export default Forget;
